package com.derbysoft.synxisadapter.dswitch3.handler.impl;

import com.derbysoft.dswitch.dto.common.KeyValue;
import com.derbysoft.dswitch.remote.hotel.dto.HotelAvailRequest;
import com.derbysoft.dswitch.remote.hotel.dto.HotelAvailResponse;
import com.derbysoft.synxisadapter.commons.log.TransactionLogger;
import com.derbysoft.synxisadapter.commons.model.OperationType;
import com.derbysoft.synxisadapter.commons.model.TransactionLog;
import com.derbysoft.synxisadapter.dswitch3.handler.RemoteServiceHandler;
import com.derbysoft.synxisadapter.dswitch3.service.HotelProviderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;
import org.springframework.util.StopWatch;

import java.util.Date;

/**
 * User: jason
 * Date: 2012-11-21
 */
@Component("ds3AvailabilityHandler")
public class AvailabilityHandler extends AbstractHandler<HotelAvailRequest, HotelAvailResponse>
        implements RemoteServiceHandler<HotelAvailRequest, HotelAvailResponse> {

    @Autowired
    @Qualifier("ds3AvailabilityService")
    private HotelProviderService<HotelAvailRequest, HotelAvailResponse> ds3AvailabilityService;

    @Override
    public HotelAvailResponse handle(HotelAvailRequest request) {
        TransactionLog transactionLog = TransactionLogger.getTransactionLogger().get();
        if (transactionLog == null) {
            transactionLog = createTransactionLog();
            TransactionLogger.getTransactionLogger().set(transactionLog);
        }

        StopWatch stopWatch = new StopWatch();
        stopWatch.start();

        HotelAvailResponse response = ds3AvailabilityService.execute(request);

        stopWatch.stop();
        long elapsedTime = stopWatch.getTotalTimeMillis();

        if (transactionLog.getOperationType() == OperationType.HOTEL_AVAIL) {
            transactionLog.setTimespan(elapsedTime);
            appendLogDetail(request, response);
            response.getElapsedTimes().add(new KeyValue(ElapsedTimeType.SYNXIS_ADAPTER.name(), String.valueOf(elapsedTime)));
        }
        return response;
    }

    private TransactionLog createTransactionLog() {
        TransactionLog transactionLog = new TransactionLog();
        transactionLog.setTimestamp(new Date());
        transactionLog.setOperationType(OperationType.HOTEL_AVAIL);
        return transactionLog;
    }
}
